import socket, os

tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_client_socket.connect(("127.0.0.1", 8080))

down_path = input("请输入下载路径：\n")
file_name = input("请输入要下载的文件：\n")
all_path = os.path.join(down_path, file_name)

tcp_client_socket.send(all_path.encode())
all_path = os.path.join(down_path, file_name)

try:
    all_files = os.listdir(down_path)
    if file_name in all_files:
        try:
            with open(os.getcwd() + '\\' + file_name, 'wb') as file:
                while True:
                    file_data = tcp_client_socket.recv(1024)
                    if file_data:
                        file.write(file_data)
                    else:
                        break
        except Exception as e:
            print("下载异常", e)
        else:
            print(file_name, "下载成功")
        tcp_client_socket.close()
    else:
        print("指定文件不存在")
except FileNotFoundError as e:
    print("指定路径不存在")
